import { useUserStore } from "@/stores/user";
import type { BaseResponse } from "@/types";
import { getToken } from "@/utils/auth";
import axios, { type AxiosRequestConfig } from "axios";
import { ElMessage } from "element-plus";

const axiosIns = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 50000,
  method: 'post',
  headers: {
    'Content-Type': "application/json; charset=utf-8"
  }
});

axiosIns.interceptors.request.use(function (config) {
  // 添加token
  config.headers = {
    token: getToken()
  };
  
  return config;
}, function (error) {
  ElMessage.error(error.message);
  return Promise.reject(error);
});

axiosIns.interceptors.response.use(function (response) {
  const { errorCode, data, errorMsg } = response.data as BaseResponse;
  if (errorCode !== null) {
    ElMessage.error(errorMsg);
    return Promise.reject(new Error(errorMsg || '请求失败'));
  }
  
  // 只返回数据，不返回状态和消息 
  return data;
}, function (error) {

  console.log(error)
  
  //登录失效
  if(error.response.status === 401) {
    ElMessage.error(error.response.data.msg);
    useUserStore().exit();
    return Promise.reject(new Error(error.response.data.msg));
  }

  if(error.response?.data?.msg) {
    ElMessage.error(error.response.data.msg);
  }else {
    ElMessage.error(error.message);
  }
  
  return Promise.reject(error);
});

function request<T = any>(config: AxiosRequestConfig): Promise<T> {
  return axiosIns(config);
}

export { axiosIns, request };
